// 云函数入口文件
const cloud = require('wx-server-sdk')
const md5 = require('md5-node')

cloud.init()


const db = cloud.database();
const collectTable = db.collection('oil_logs');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  /*
  *  提交加油时间(若没有取服务器当前时间)、当前里程、加油量、单价、总价、加油状态(FULL 加满跳枪、LIGHT 亮灯~当前版本暂时不做计算、FORGET 上次忘记~当前版本暂时不做计算),油品类型、加油站（可选）、备注（可选）
  *miles 当前表显里程
  *createdTime 加油时间
  *quantity 加油的数量(L)
  *price 燃料单价
  *totalPrice 加油花费金额
  *remarks 备注
  *state  加油状态
  *stationId  加油站ID
  *oilType    燃料类型
  */
  var reg = /^\d+(?=\.{0,1}\d+$|$)/



 if (event.miles == '' || event.miles==null) {
    return {
      code: 400,
      msg:'公里数不能为空'
    }
  }
  if (event.createdTime == '' || event.createdTime == null) {
    return {
      code: 400,
      msg: '加油时间不能为空'
    }
  }
  if (event.price == '' || event.price == null) {
    return {
      code: 400,
      msg: '燃料单价不能为空'
    }
  }
  if (event.totalPrice == '' || event.totalPrice == null) {
    return {
      code: 400,
      msg: '花费总金额不能为空'
    }
  }
  if (event.quantity == '' || event.quantity == null) {
    return {
      code: 400,
      msg: '加油数量不能为空'
    }
  } 

  let saveData = {};
  saveData.miles = event.miles;
  saveData.created_time = new Date(event.createdTime);
  saveData.quantity = Number(event.quantity);
  saveData.price = Number(event.price);
  saveData.total_price = Number(event.totalPrice);
  saveData.remarks = event.remarks;
  saveData.state = event.state;
  saveData.station_id = event.stationId;
  saveData.oil_type = event.oilType;
  saveData.oil_consumption = ''
  saveData.diff_miles = 0
  saveData.openid = md5(wxContext.OPENID)


  try {
    //查询当前用户的所有加油数据
    const res = await collectTable.where({
      openid: md5(wxContext.OPENID)
    }).limit(1).orderBy('created_time', 'desc').get();
    let diff_miles = 0
    let lastData =null;
    let oilConsumption = 0; //油耗初始值为0
    if(!res){
      return {
        code: 500,
        msg: '查询油耗数据出错'
      }
    }


    //根据用户提交的数据更新对应油站、对应标号燃料价格（用户选择了油站+标号）
    if (saveData.station_id && saveData.oil_type) {
      const updateRes = await cloud.callFunction({
        // 要调用的云函数名称
        name: 'updateOilPrice',
        // 传递给云函数的参数
        data: {
          stationId: saveData.station_id,
          price: saveData.price,
          oilType: saveData.oil_type
        }
      })
    }


    if (res.data && res.data.length>0) {//当前openid存在最新一条油耗数据,进行比对取值计算油耗
      lastData = res.data[0]
      diff_miles = Number(event.miles - lastData.miles)
      if (!reg.test(diff_miles)) {
        return {
          code: 500,
          msg:'请核实公里数，不能比上一次少',
          data: diff_miles
        }
      } else { //继续
        saveData.diff_miles = diff_miles
        //计算油耗，如果上一次是加满，这一次也是加满，那么可以进行公里数/加油数量*100
        if (lastData.state == 'FULL' && event.state == 'FULL') {
          oilConsumption = (Number(event.quantity) / diff_miles * 100).toFixed(2)
        } else { //油耗不计算
          oilConsumption = ''
        }
        //存储数据
        saveData.oil_consumption = oilConsumption

        let addOk = await collectTable.add({
          data: saveData
        })

        if (addOk) {
          return {
            code: 200,
            msg: '保存成功'
          }
        } else {
          return {
            code: 500,
            msg: '服务器原因，保存出错'
          }
        }
      }
    } else { //直接存储数据
      let addOk = await collectTable.add({
        data: saveData
      })

      if (addOk) {
        return {
          code: 200,
          msg: '保存成功'
        }
      }else{
        return {
          code: 500,
          msg: '服务器原因，保存出错'
        }
      }
      
    }



  } catch (err) {
    return {
      code: 500,
      msg: '服务器原因，保存出错'
    }
  }

}